$(function () {
    $('input[type=text], input[type=password]').placeholder();
    $('#registerButton').hover(function () { $('#registerInfoBox').toggleClass('active'); });

    snippetBox.init();
});

var snippetBox = {};

snippetBox.init = function () {
    snippetBox.favorite.init();
    snippetBox.markup.init();
    snippetBox.status.init();
}

snippetBox.markup = {
    refreshTimer: null,

    init: function () {
        this.styleCode();
    },

    styleCode: function () {
        if (typeof prettyPrint == 'undefined') return;
        var hascode = false;
        $("pre > code").parent().each(function () {
            if (!$(this).hasClass('prettyprint')) {
                $(this).addClass('prettyprint');
                hascode = true;
            }
        });
        if (hascode) { prettyPrint(); }
    },

    editor: function () {
        $('.markdownEditor').change(function () {
            snippetBox.markup.styleCode();
        }).keyup(function () {
            snippetBox.markup.startTimerForStyling();
        });

        snippetBox.markup.startTimerForStyling();
    },

    startTimerForStyling: function () {
        clearTimeout(snippetBox.markup.refreshTimer);

        snippetBox.markup.refreshTimer = setTimeout(function () {
            snippetBox.markup.styleCode(); 
        }, 600);
    }
}

snippetBox.status = {
    init: function () {
        var timer;
        if ($('.message').length > 0) {
            timer = setTimeout(function () { $('.message').fadeOut(); }, 2000);

            $('.message').hover(function () {
                if (timer != null)
                    clearTimeout(timer);
            }, function () {
                timer = setTimeout(function () { $('.message').fadeOut(); }, 2000);
            });
        }
    }
}

snippetBox.favorite = {
    init: function () {
        $('.favorite').click(snippetBox.favorite.toggleFavorite);
    },

    toggleFavorite: function (e) {
        e.preventDefault();

        var self = $(this);
        var id = self.parents('article').attr('id');

        $.post(self.attr('href'), function () {
            self.toggleClass('active');
        });
    }
}

snippetBox.settings = {
    init: function () {
        $('#settingsTabs li a').click(function (e) {
            e.preventDefault();

            var tabName = $(this).attr('href').replace('#', '');
            snippetBox.settings.showTab(tabName);
        });

        var tab = $('#settingsTabs a:first');
        var tabName = tab.attr('href').replace('#', '');

        if (localStorage && localStorage.settingsTab != null)
            tabName = localStorage.settingsTab;

        snippetBox.settings.showTab(tabName);

        $(".toggleBox :checkbox").change(function () {
            $(this).parents(".toggleBox").toggleClass("checked");
        });
    },

    showTab: function (tabName) {
        $('#settingsTabs a').removeClass('current');
        $('#settingsTabs .' + tabName).addClass('current');

        $('.settingsGroup').hide();
        $('#' + tabName).show();

        if (localStorage)
            localStorage.settingsTab = tabName;
    }
}

snippetBox.profile = {
    init: function() {
        // preload loading gif
        var image = new Image();
        image.src = '/assets/images/load-loading.gif';

        $(".infyPaging").infyPaging();
    }
}

snippetBox.themePicker = {
    init: function (pickerId, currentTheme) {
        var defaultThemeStyle = $('link[href*=themes]:first');
        var defaultPath = defaultThemeStyle.attr('href');
        var basePath = defaultPath.substring(0, defaultPath.indexOf('/themes/') + '/themes/'.length);
        
        $('#' + pickerId + ' .theme').click(function () {
            var theme = $('input', this).val();
            snippetBox.themePicker.setTheme(basePath, theme);
        });
    },

    setTheme: function (basePath, name) {
        $('link[href*=themes]:first').attr('href', basePath + name + '/' + name + '.css');
    }

}

var timings = {};

timings.init = function () {
    var now = new Date().getTime();
    var page_load_time = now - performance.timing.navigationStart;
    $('#jsTimings').html('<br><b>Client</b>: Perceived Loading Time: ' + page_load_time + 'ms.');
}

$.fn.extend({
    infyPaging: function () {
        return this.each(function () {
            $(this).click(function (e) {
                e.preventDefault();
                var self = $(this);
                var page = parseInt(self.data('page'));
                var pageCount = parseInt(self.data('page-count'));
                var nextPage = page + 1;
                var url = self.data('url').replace('{0}', nextPage);

                if (page == pageCount) {
                    return;
                }

                self.addClass('loading');

                $.ajax({
                    url: url,
                    success: function (resp) {
                        $('#' + self.data('append-to')).append(resp)
                        self.data('page', nextPage);
                        self.removeClass('loading');

                        if (nextPage == pageCount) {
                            self.remove();
                        }
                    },
                    error: function () {
                        alert('Sorry, could not get the next page. Please try again later.');
                        self.removeClass('loading');
                    }
                });
            });
        });
    }
});